package builderdto

import (
	"yunj/pkg/yunj/util"
)

// 请求参数
type TableRequestParam struct {
	BuilderId            any   `json:"builder_id"`
	BuilderAsyncType     any   `json:"builder_async_type"`
	State                any   `json:"state"`
	Pks                  []any `json:"pks"`
	stringPks            []string
	uint64Pks            []uint64
	EventLocation        string         `json:"event_location"`          // 事件位置
	EventCode            any            `json:"event_code"`              // 事件code
	EventConfirmFormData map[string]any `json:"event_confirm_form_data"` // 事件确认表单数据
	Filter               string         `json:"filter"`                  // json字符串 map[string]any
	filterData           map[string]any
	uint64FilterData     map[string]any
	Page                 int `json:"page"`
	PageSize             int `json:"page_size"`
	offset               int
	limit                int
	Sort                 *TableSort   `json:"sort"`
	Export               *TableExport `json:"export"`
}

// 判断是否是count请求
func (p *TableRequestParam) IsCountRequest() bool {
	return p.BuilderAsyncType == "count"
}

func (p *TableRequestParam) StringPks() []string {
	if p.stringPks == nil {
		p.stringPks = make([]string, 0, len(p.Pks))
		for _, pk := range p.Pks {
			if stringPk, err := util.ToString(pk); err == nil {
				p.stringPks = append(p.stringPks, stringPk)
			}
		}
	}
	return p.stringPks
}

func (p *TableRequestParam) Uint64Pks() []uint64 {
	if p.uint64Pks == nil {
		p.uint64Pks = make([]uint64, 0, len(p.Pks))
		for _, pk := range p.Pks {
			if uin64Pk, err := util.ToUint64(pk); err == nil {
				p.uint64Pks = append(p.uint64Pks, uin64Pk)
			}
		}
	}
	return p.uint64Pks
}

func (p *TableRequestParam) FilterData() map[string]any {
	if p.filterData == nil {
		p.filterData = make(map[string]any)
		if filterData, err := util.JsonTo[map[string]any](p.Filter); err == nil {
			p.filterData = filterData
		}
	}
	return p.filterData
}

func (p *TableRequestParam) Uint64FilterData() map[string]any {
	if p.uint64FilterData == nil {
		p.uint64FilterData = make(map[string]any)
		if uint64FilterData, err := util.JsonTo[map[string]any](p.Filter); err == nil {
			p.uint64FilterData = util.MapFloat64ToUints(uint64FilterData)
		}
	}
	return p.uint64FilterData
}

func (p *TableRequestParam) Offset() int {
	if p.offset == 0 {
		p.offset = p.PageSize * (p.Page - 1)
	}
	return p.offset
}

func (p *TableRequestParam) Limit() int {
	if p.limit == 0 {
		p.limit = p.PageSize
	}
	return p.limit
}

// Equal 判断传入值是否等于state，支持类型转换比较
func (p *TableRequestParam) StateEqual(value any) bool {
	return util.EqualTo(p.State, value)
}

// Equal 判断传入值是否等于event_code，支持类型转换比较
func (p *TableRequestParam) EventCodeEqual(value any) bool {
	return util.EqualTo(p.EventCode, value)
}
